/**
 * @Author: zc
 * @Date: 2019-11-29 10:14:39
 * @LastEditors: zc
 * @LastEditTime: 2020-08-27 17:32:31
*/
const cmd = require('node-cmd')
const fs = require('fs')
const path = require('path')

const dotenv = require("dotenv")
dotenv.config()

const { REACT_APP_ONLINE_BRANCH, npm_package_name } = process.env
const pathName = npm_package_name
const onlineBranch = REACT_APP_ONLINE_BRANCH
let copyFlieName = ''
let copyFilePath = '.'
let currentBranchName = ''

// 获取 目标文件夹的绝对路径
function getGoal(cpFolder = '../build') {
  return path.resolve(__dirname, cpFolder) + '/'
}

function handleError(functionName, err) {
  console.log('error', err)
  console.log(`${functionName}报错啦~请根据报错解决响应的问题`)
}

// 获取当前分支名
function current_branch() {
  cmd.get(
    `git symbolic-ref --short -q HEAD`,
    (err, data) => {
      if (!err) {
        currentBranchName = data.replace(/[\r\n]/g, "")
        handleCopyBuild()
      } else {
        handleError('current_branch', err)
      }
    }
  )
}

function handleCopyBuild() {
  const goal = getGoal()
  copyFlieName = `${pathName}_COPY_${currentBranchName}`
  cmd.get(
    ` cd ..
      mkdir -p ${copyFlieName}
      cd ${copyFlieName}
      mkdir -p build
      cp -r ${goal} ./build
    `,
    err => {
      if (!err) {
        copyFilePath = getGoal(`../../${copyFlieName}`)
        handleChekoutMaster()
      } else {
        handleError('handleCopyBuild', err)
      }
    }
  )
}

function handleChekoutMaster() {
  if (!onlineBranch || onlineBranch === 'develop') {
    return console.log(`方法${handleChekoutMaster}执行错误，因为切换分支${onlineBranch}不可操作`)
  }
  cmd.get(
    ` cd ../${pathName}
      git add .
      git commit -m 'build: ${currentBranchName}分支上线更新提交'
      git push
      git checkout ${onlineBranch}
      git pull
    `,
    err => {
      if (!err) {
        fs.access('./src', err => {
          handleCopytoMaster(err ? false : true)
        })
      } else {
        handleError('handleChekoutMaster', err)
      }
    }
  )
}

function handleCopytoMaster (exists) {
  let _cmd = exists ? 
  ` rm -rf ./public ./mocks ./src ./*.log
  ` : ''
  cmd.get( 
    ` ${_cmd}
      rm -rf ./build
      mkdir -p build
      cp -r ${copyFilePath}/build/ ./build/
    `,
    err => {
      if (!err) {
        handleMaster()
      } else {
        handleError('handleCopytoMaster', err)
      }
    }
  )
}

function handleMaster() {
  cmd.get(
    ` cd ..
      rm -rf ./${copyFlieName}
      cd ${pathName}
      git add .
      git commit -m 'build: ${currentBranchName}分支编译后的文件 上线更新提交'
      git push origin ${onlineBranch}
    `, 
    (err, data) => {
    console.log(data)
    if (!data) {
      console.log(`尝试再次提交...`)
      return cmd.get(
        `git add . 
         git commit -m 'build: 提交上线更新代码为${currentBranchName}分支编译后的代码'
         git push 
         git checkout ${currentBranchName}`,
        err => {
          if (!err) console.log(`master上线分支代码已提交，快去就 j-one 上线吧 --> ${pathName}`)
        }
      )
    }
    if (!err) {
      cmd.get(
        `git checkout ${currentBranchName}`, 
        err => {
        if (!err) console.log(`更新至master上线分支，快去就 j-one 上线吧 --> ${pathName}`)
        else handleError('handleMaster', err)
      })
    }
  })
}
current_branch()
